import { Component } from '@angular/core';
import { Store } from '@ngxs/store';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';
import { ShopSelector } from '@shop/store/shop.selector';
import { ShopAction } from '@shop/store/shop.action';

@Component({
  selector: 'app-cart',
  template: `
    <div *ngIf="(showCount$|async)||false">
      <button nz-button nzType="primary" (click)="gotoCheckout()">下单</button>
      &nbsp;
      <span>总价:{{(cartTotalPrice$|async) || 0}}</span>
    </div>
    <div>
      <nz-table #basicTable [nzData]="(cartList$|async)||[]">
        <thead>
        <tr>
          <th>名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let data of basicTable.data">
          <td>{{data.name}}</td>
          <td>{{data.price}}</td>
          <td>
            <nz-input-number [ngModel]="data.count" [nzMax]="20000" [nzStep]="1"
                             (ngModelChange)="changeCount($event,data)"></nz-input-number>
          </td>
          <td>{{data.price * data.count}}</td>
          <td>
            <a (click)="deleteFromCart(data)">删除</a>
          </td>
        </tr>
        </tbody>
      </nz-table>
    </div>
  `,
  styles: [],
})
export class CartComponent {
  @AutoUnsubscribe() cartList$ = this.store.select(ShopSelector.cartList);
  @AutoUnsubscribe() cartTotalPrice$ = this.store.select(ShopSelector.cartTotalPrice);
  @AutoUnsubscribe() showCount$ = this.store.select(ShopSelector.showCount);

  constructor(
      private store: Store,
  ) {
  }

  gotoCheckout() {
    this.store.dispatch(new ShopAction.GotoCheckout());
  }

  changeCount($event: any, data: any) {
    this.store.dispatch(new ShopAction.ChangeCount($event, data));
  }

  deleteFromCart(data: any) {
    this.store.dispatch(new ShopAction.ChangeCount(0, data));
  }
}
